import { Component, OnInit } from '@angular/core';
import { NzCascaderOption, NzMessageService } from 'ng-zorro-antd';
import { FetchService } from '../../../../core/net/fetch.service';
import * as moment from 'moment';

@Component({
    selector: 'app-dd-inlet',
    templateUrl: './dd-inlet.component.html',
    styleUrls: ['./dd-inlet.component.scss']
})
export class DdInletComponent implements OnInit {
    gateIds: string[] | null = null;
    contentTitle: string;
    today = new Date();
    gateDetailData = [];
    tableTitle = '实引水量';
    isTableEditable = false;
    editCache: { [key: string]: { edit: boolean; data: any } } = {};
    dataCache = {};
    sectionId = JSON.parse(localStorage.userInfo).sectionId;
    constructor(private fetchService: FetchService,
                private message: NzMessageService) {
    }

    ngOnInit(): void {
    }

    loadGateData(node: NzCascaderOption, index: number): PromiseLike<void> {
        return new Promise(resolve => {
            const params = {
                pid: index < 0 ? '0' : node.value,
                pageSize: 10000
            };
            this.fetchService
                .post('plan/wrsReportRelation/list', params)
                .subscribe(res => {
                    node.children = res['list'].map(item => {
                        if (this.sectionId === '1') {
                            if (item['menu'] === 1) {
                                return {
                                    value: item.id,
                                    label: item.name,
                                    isLeaf: true
                                };
                            } else {
                                return {
                                    value: item.id,
                                    label: item.name
                                };
                            }
                        } else {
                            return {
                                value: item.id,
                                label: item.name,
                                isLeaf: true
                            };
                        }
                    });
                    resolve();
                });
        });
    }

    onGateChanges(ids: string[]): void {
        this.isTableEditable = false;
        if (!!ids.length) {
            this.fetchService
                .post('plan/wrsReportRelation/list', {
                    pid: ids[ids.length - 1],
                    pageSize: 10000
                })
                .subscribe(res => {
                    this.gateDetailData = res['list'] || [];
                    this.getGridData();
                });
        } else {
            this.gateDetailData = [];
            this.updateEditCache();
        }
    }

    getGridData(): void {
        this.tableTitle = `${moment(this.today).year()}年${moment(this.today).month() + 1}月${moment(this.today).date()}日斗口实引水量`;
        this.fetchService.post('plan/wrsReportWaterDay/list', {
            y: moment(this.today).year(),
            m: moment(this.today).month() + 1,
            d: moment(this.today).date()
        }).subscribe(res => {
            this.dataCache = res['list'][0] || {};
            this.gateDetailData.forEach(item => {
                item['water'] = this.dataCache[item['val']];
            });
            this.updateEditCache();
        });
    }

    updateEditCache(): void {
        this.gateDetailData.forEach(item => {
            this.editCache[item.id] = {
                edit: false,
                data: { ...item }
            };
        });
    }

    startEdit(): void {
        this.isTableEditable = true;
        this.gateDetailData.forEach(item => {
            this.editCache[item.id] = {
                edit: false,
                data: { ...item }
            };
        });
        Object.keys(this.editCache).forEach(key => {
            this.editCache[key].edit = true;
        });
    }

    saveEditData(): void {
        if (this.gateDetailData.length) {
            this.gateDetailData.forEach(item => {
                Object.assign(item, this.editCache[item.id].data);
                this.editCache[item.id].edit = false;
            });
            const data = this.getSubmitData(this.gateDetailData);
            this.fetchService.post('plan/wrsReportWaterDay/add', {
                y: moment(this.today).year(),
                m: moment(this.today).month() + 1,
                d: moment(this.today).date(),
                ...data
            }).subscribe(res => {
                this.isTableEditable = false;
                this.message.success('保存成功！');
                this.getGridData();
            });
        } else {
            this.isTableEditable = false;
        }
    }

    resetEditData(): void {
        this.message.info('重置成功！');
        Object.keys(this.editCache).forEach((key, index) => {
            this.editCache[key].edit = false;
            this.editCache[key].data = { ...this.gateDetailData[index] };
        });
    }

    cancelEdit(): void {
        this.isTableEditable = false;
        this.getGridData();
    }

    private getSubmitData(data): any {
        const result = this.dataCache;
        data.forEach(item => {
            result[item.val] = item.water;
        });
        return result;
    }
}
